package com.guava.mall.tool.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @Description:
 * @Auth: DengYunHu
 * @Date: 2021/1/21 16:03
 */
@Slf4j
public class ThreadPoolUtils {
    private static final int CORE_POOL_SIZE = 25;
    private static final int MAX_POOL_SIZE = 35;
    private static final long KEEP_LIVE_TIME = 60L;
    private static final int BLOCK_QUEUE_SIZE=10000;
    private static final BlockingQueue<Runnable> BLOCKING_QUEUE = new LinkedBlockingQueue<>(BLOCK_QUEUE_SIZE);
    private static final ThreadPoolExecutor POOL;

    static {
        POOL = new ThreadPoolExecutor(CORE_POOL_SIZE,
                MAX_POOL_SIZE,
                KEEP_LIVE_TIME,
                TimeUnit.MILLISECONDS,
                BLOCKING_QUEUE,
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy());
    }

    public static void execute(Runnable runnable) {
        POOL.execute(runnable);
    }

    public static void shutDown() {
        boolean shutdown = POOL.isShutdown();
        if (!shutdown) {
            POOL.shutdown();
        }
    }

    public static <T> T execute(Callable<T> callable, long timeOut) {
        Future<T> submit = POOL.submit(callable);
        try {
            return submit.get(timeOut, TimeUnit.SECONDS);
        } catch (TimeoutException e) {
            submit.cancel(true);
            log.error("任务执行超时");
        } catch (Exception e) {
            log.error("任务执行出现未知异常", e);
        }
        return null;
    }

    public static void shutDownNow() {
        POOL.shutdownNow();
    }

    public static void remove(Runnable runnable) {
        BLOCKING_QUEUE.remove(runnable);
    }
}
